/*
 *    Copyright 2006-2021 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.fastjrun.codeg.javamapper.elements.sqlprovider;

import com.fastjrun.codeg.common.Common;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.codegen.mybatis3.ListUtilities;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.sqlprovider.AbstractJavaProviderMethodGenerator;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import static org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities.getEscapedColumnName;
import static org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities.getParameterClause;
import static org.mybatis.generator.internal.util.StringUtility.escapeStringForJava;

public class ProviderInsertBatchMethodGenerator extends AbstractJavaProviderMethodGenerator {

  public ProviderInsertBatchMethodGenerator(boolean useLegacyBuilder) {
    super(useLegacyBuilder);
  }

  @Override
  public void addClassElements(TopLevelClass topLevelClass) {
    Set<String> staticImports = new TreeSet<>();
    Set<FullyQualifiedJavaType> importedTypes = new TreeSet<>();

    if (useLegacyBuilder) {
      staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.BEGIN"); // $NON-NLS-1$
      staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.FROM"); // $NON-NLS-1$
      staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.SELECT"); // $NON-NLS-1$
      staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.SQL"); // $NON-NLS-1$
    } else {
      importedTypes.add(NEW_BUILDER_IMPORT);
    }

    FullyQualifiedJavaType fqjt = introspectedTable.getRules().calculateAllFieldsClass();
    importedTypes.add(fqjt);

    Method method = new Method(Common.INSERTBATCH);
    method.setVisibility(JavaVisibility.PUBLIC);
    method.setReturnType(FullyQualifiedJavaType.getStringInstance());

    method.addParameter(
        new Parameter(
            new FullyQualifiedJavaType(
                "java.lang.List<" + fqjt.getShortName() + ">"), // $NON-NLS-1$
            "records")); //$NON-NLS-1$

    context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);

    method.addBodyLine("SQL sql = new SQL();"); // $NON-NLS-1$

    method.addBodyLine(
        String.format(
            "sql.INSERT_INTO(\"%s\");", //$NON-NLS-1$
            escapeStringForJava(introspectedTable.getFullyQualifiedTableNameAtRuntime())));

    method.addBodyLine(""); // $NON-NLS-1$
    for (IntrospectedColumn introspectedColumn :
        ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns())) {

      if (!introspectedColumn.getFullyQualifiedJavaType().isPrimitive()
          && !introspectedColumn.isSequenceColumn()) {
        method.addBodyLine(
            String.format(
                "sql.INTO_COLUMNS(\"%s\");", //$NON-NLS-1$
                escapeStringForJava(getEscapedColumnName(introspectedColumn))));
      }
    }
    method.addBodyLine("StringBuilder sqlSB=new StringBuilder(sql.toString()).append(\"values\");");
    method.addBodyLine("for (int i=0;i<records.size();i++){");
    method.addBodyLine("if(i>0){");
    method.addBodyLine("sqlSB.append(\",\");");
    method.addBodyLine("}");
    method.addBodyLine("StringBuilder sb=new StringBuilder();");
    List<IntrospectedColumn> introspectedColumns =
        ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns());
    for (int index = 0; index < introspectedColumns.size(); index++) {
      IntrospectedColumn introspectedColumn = introspectedColumns.get(index);

      if (!introspectedColumn.getFullyQualifiedJavaType().isPrimitive()
          && !introspectedColumn.isSequenceColumn()) {
        if (index == introspectedColumns.size() - 1) {
          method.addBodyLine(
              "sb.append(\""
                  + getParameterClause(introspectedColumn, "records[\"+i+\"].")
                  + "\");");
        } else {

          method.addBodyLine(
              "sb.append(\""
                  + getParameterClause(introspectedColumn, "records[\"+i+\"].")
                  + ",\");");
        }
      }
    }

    method.addBodyLine("sqlSB.append(\"(\").append(sb).append(\")\");");

    method.addBodyLine("}"); // $NON-NLS-1$
    method.addBodyLine("return sqlSB.toString();"); // $NON-NLS-1$

    if (context
        .getPlugins()
        .providerInsertSelectiveMethodGenerated(method, topLevelClass, introspectedTable)) {
      topLevelClass.addImportedTypes(importedTypes);
      topLevelClass.addMethod(method);
    }
  }
}
